<%@page contentType="text/html; charset=utf-8"%>
<%@include file="/WEB-INF/views/common/taglibs.jspf" %>
<title>系统用户管理</title>

<div class="page-header">
	<h1>
		系统用户列表 
	</h1>
</div>
<div class="row">
	<div class="col-xs-12">
		<div class="row">
			<div class="col-xs-9">
				<form id="search_form" style="float:left;">
					<span class="input-icon">
						<input id="quickSearch" type="text" style="padding-top:8px;" class="input-sm" name="quickSearch" placeholder="快速搜索 ...">
						<i class="ace-icon fa fa-search blue" style="font-size:14px;"></i>
					</span>
					<span class="input-icon">
						<input type="text" class="date-picker input-sm input-medium" name="startTime" placeholder="开始日期 ">
						<i class="ace-icon fa fa-calendar blue"></i>
					</span>
					<span class="input-icon">
						<input type="text" class="date-picker input-sm input-medium" name="endTime" placeholder="结束日期 ">
						<i class="ace-icon fa fa-calendar blue"></i>
					</span>
					<span class="input-icon" style="float:left;">
						<select name="status">
							<option value="" selected="selected">账户状态</option>
							<option value="normal">正常</option>
							<option value="blocked">禁用</option>
						</select>
					</span>
					
					<input type="hidden" name="deleted" value="0" id="deleted">
				</form>
				<button class="btn btn-purple btn-xs height-30" onclick="oSearch();">
					<i class="ace-icon fa fa-search bigger-120"></i>
					搜索
				</button>
				<button class="btn btn-pink btn-xs height-30" onclick="$('#deleted').val(0); resetSearch();">
					<i class="ace-icon fa fa-undo bigger-120"></i>
					重置
				</button>
			</div>
			<div class="col-xs-3">
				<div class="pull-right">
					<button class="btn btn-success btn-xs height-30" onclick="formDialog();"><i class="ace-icon fa fa-plus bigger-120"></i> 新增</button>
					<button class="btn btn-info btn-xs height-30" onclick="edit();"><i class="ace-icon fa fa-pencil bigger-120"></i> 编辑</button>
					<button class="btn btn-danger btn-xs height-30" onclick="batchDel();"><i class="ace-icon fa fa-trash bigger-120"></i> 删除</button>
					<button class="btn btn-success pink btn-xs height-30" onclick="oTable.ajax.reload();"><i class="ace-icon fa fa-refresh fa-spin bigger-120"></i> 刷新</button>
				</div>
			</div>
		</div>
		<div class="space-2"></div>
		
	
		<div class="row">
			<div class="col-xs-12">
			
				<table id="oTable" class="table table-striped table-bordered table-hover">
			        <thead>
			        <tr>
			            <th class="center">
							<label class="position-relative">
								<input type="checkbox" class="ace" />
								<span class="lbl"></span>
							</label>
						</th>
			            <th>序号</th>
			            <th>编号</th>
			            <th>用户名</th>
			            <th>移动电话</th>
			            <th>邮箱地址</th>
			            <th>账户状态</th>
			            <th>是否管理员</th>
			            <th>添加时间</th>
			            <th>操作</th>
			        </tr>
			        </thead>
			        <tbody></tbody>
			        <!-- tbody是必须的 -->
			    </table>
				
			</div>
		</div>
		
		
		<!-- PAGE CONTENT ENDS -->
	</div><!-- /.col -->
</div><!-- /.row -->



<!--定义操作列按钮模板-->
<script id="func_tpl" type="text/x-handlebars-template">
    {{#each func}}
		{{#if this.show}}
		<button class="btn btn-xs btn-{{this.type}}" onclick="{{this.fn}}">
			<i class="ace-icon fa fa-{{this.icon}}"></i> {{this.name}}
		</button>
		{{/if}}
    {{/each}}
</script>
<!-- footer toolbar -->
<script id="footer_toolbar_tpl" type="text/x-handlebars-template">
	<button class="btn btn-success btn-xs" onclick="formDialog();">
		<i class="ace-icon fa fa-plus bigger-100"></i>
		新增
	</button>
	<button class="btn btn-danger btn-xs del-btn" onclick="batchDel();">
		<i class="ace-icon fa fa-trash bigger-100"></i>
	</button>&nbsp;
	<button class="btn btn-purple btn-xs py-btn" onclick="batchDel(false);">
		<i class="ace-icon fa fa-search bigger-120"></i>
		恢复
	</button>
	<button class="btn btn-purple btn-xs py-btn" onclick="batchDel(true);">
		<i class="ace-icon fa fa-search bigger-120"></i>
		物理删除
	</button>
	<button class="btn btn-purple btn-xs" onclick="searchDeleted('deleted')">
		<i class="ace-icon fa fa-search bigger-120"></i>
		已删除用户
	</button>
	<button class="btn btn-purple btn-xs" onclick="searchDeleted('all')">
		<i class="ace-icon fa fa-search bigger-120"></i>
		所有用户
	</button>&nbsp;
</script>
<script type="text/javascript">
var oTable, dialogIndex ;
var scripts = [null, null, null];
$('.page-content-area').ace_ajax('loadScripts', scripts, function() {
	jQuery(function($) {
		initDataTable() ;
		quickSearch() ;
		$('.date-picker').datepicker({language: "zh", format: "yyyy-mm-dd", autoclose: true, todayHighlight: true});
	});
});

function initDataTable() {
	var func_tpl = $("#func_tpl").html();
    var func_template = Handlebars.compile(func_tpl);	 //预编译模板
    var _url = "${ctx}/admin/sys/user/datatables" ;
    
    oTable = $("#oTable").DataTable({
		ajax: {
			url: _url,
			type: "POST",
			data: function(d){
				d.quickSearch=$("input[name=quickSearch]").val();
				d.startTime=$("input[name=startTime]").val();
				d.endTime=$("input[name=endTime]").val();
				d.status=$("select[name=status]").val();
				d.deleted=$("input[name=deleted]").val();
			}
		},
		serverSide: true, processing: true, paging: true,
		scrollCollapse: true, autoWidth: false,
		order: [[2, "desc"]], pagingType: "full_numbers", 
		lengthMenu: [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
		language: {"url": "${ctx}/static/json/dataTable-language.json"},
		dom:	"t" +
				"<'row' <'col-xs-4' <'#footer_toolbar'><'float_left'i>> <'col-xs-2' r> <'col-xs-6' <'float_right'l><'float_right'p>> > ",
		columns: [
               {"data": null, sWidth: 50, sClass: "center", bSortable: false},
               {"data": null, sWidth: 80, sClass: "center", bSortable: false, searchable: false},
               {"data": "id", sWidth: 80, sClass: "center", bSortable: true, defaultContent : ""},
               {"data": "username", sWidth: 120, bSortable: true, defaultContent : ""},
               {"data": "mobile_phone_number", sWidth: 120, bSortable: true, defaultContent : ""},
               {"data": "email", sWidth: 200, bSortable: true, defaultContent : ""},
               {"data": "status", sWidth: 80, sClass: "center", bSortable: true, defaultContent : "", render: function(data, type, row, meta){
            	   return (data == "normal"?"<span style='color:green'>正常</span>":"<span style='color:red'>锁定</span>");
               }},
               {"data": "admin", sWidth: 100, sClass: "center", bSortable: true, defaultContent : "", render: function(data, type, row, meta){
            	   return (data == true?"<span style='color:red'>是</span>":"否");
               }},
               {"data": "createTime", sWidth: 120, bSortable: true, sDefaultContent : "", render: function(data, type, row, meta){
            	   return $.date.format(data, "yyyy-mm-dd") ;
               }},
               {"data": null, "bSortable": false}
		],
		columnDefs: [{
			targets: 0,
			render: function (data, type, row, meta) {
				var s = '<label class="position-relative"><input type="checkbox" class="ace" /><span class="lbl"></span></label>';
				return s;
			}
		},{
			targets: 3,
			render: function (data, type, row, meta) {
				if(row.deleted == true) {
					return "<span class='deleted'>"+data+"</span>" ;
				} else {
					return data ;
				}
			}
		},{
			targets: 9,
			render: function (data, type, row, meta) {
				var context = {
						func: [
						       {"name": "编辑", "type": "info", "icon": "pencil-square-o", "fn": "formDialog(\'" + row.id + "\')", "show": (row.deleted==true?false:true)}, 
						       {"name": "删除", "type": "danger", "icon": "trash", "fn": "del(\'" + row.id + "\')", "show": (row.deleted==true?false:true)}
						]
				};
				var html = func_template(context);
				return html;
			}
		}],
		initComplete: function(){
			var footer_toolbar_tpl = $("#footer_toolbar_tpl").html() ;
			var footer_toolbar_template = Handlebars.compile(footer_toolbar_tpl);
			$("#footer_toolbar").addClass("float_left").append(footer_toolbar_template());
			$(".py-btn").hide() ;
			
		},
		drawCallback: function() {
			$(".deleted").closest("tr").css("text-decoration", "line-through");
		}
				
	});
	
	//序号
	oTable.on("draw", function () {
		oTable.column(1, {search:'applied', order:'applied'}).nodes().each( function (cell, i){
			cell.innerHTML = i+1;
        });
	});
	//复选框-全选
	oTable.on("click", "thead tr th input:checkbox" , function(){
		var that = this ;
		$(this).closest('table').find('tr > td:first-child input:checkbox').each(function(){
			if(this.checked == false) {
				that.checked = true;
				this.checked = true ;
				$(this).closest("tr").addClass('selected') ;
				$("#oTable").removeClass('table-striped');
			}else if(this.checked == true) {
				this.checked = false ;
				$(this).closest("tr").removeClass('selected') ;
			}
			if(!$("#oTable tbody tr").hasClass("selected")) {
				$("#oTable").addClass('table-striped');
				that.checked = false;
			}
		});
	});
	//复选框-多选
	oTable.on("click", "tbody tr td input:checkbox" , function(){
		$("#oTable").removeClass('table-striped');
		$(this).closest("tr").toggleClass('selected') ;
		
		if(!$("#oTable tbody tr").hasClass("selected")) {
			$("#oTable").addClass('table-striped');
		}
	});
	
	$.fn.dataTable.ext.errMode = function(e, settings, techNote, message) {};
	oTable.on("error.dt", function(e, settings, techNote, message){
		oTable.destroy();
		layer.msg('数据加载发生异常发生错误！', { icon: 2, time: 2000, shade: [0] }); 
	});
	
	
}

function formDialog(id){
	var url = "${ctx}/admin/sys/user/form" ;
	if(undefined != id && id != "") {
		url = "${ctx}/admin/sys/user/form?id="+id ;
	}
	var loadIndex = layer.load(0, {shade : [0.3]});
	$.ajax({
		url: url, cache:false
	}).error(function(event, XMLHttpRequest, ajaxOptions, thrownError){
		if(event.status == 404) {layer.close(loadIndex); $.dialog.tips("404请求地址不正确！", 2, "fa-times red"); } 
		else {layer.close(loadIndex); $.dialog.tips("请求发生错误，错误代码："+event.status, 2, "fa-times red"); }
	}).done(function(result){
		dialogIndex = layer.open({
		    type: 1, //page层
		    area: ['900px', '500px'],
		    title: (undefined==id?'添加':'编辑'),
		    skin: 'seaning', //墨绿风格
		    shade: 0.6, //遮罩透明度
		    shift: 2, //0-6的动画形式，-1不开启 
		    scrollbar: false, //禁用浏览器滚动条
		    content: result,
		    success: function(layero, index){ layer.close(loadIndex); },
		    btn: ['提交', '取消'],
		    yes: function(index, layero){
		    	if(undefined == id) {
		    		ajax("${ctx}/admin/sys/user/add") ;
		    	} else {
		    		ajax("${ctx}/admin/sys/user/update") ;
		    	}
		    },cancel: function(index){}
		}); 
	});
};

function ajax(_url) {
	if($("#form").valid()) {
		var msgIndex = layer.msg('数据提交中...', { icon: 17, shade: [0]}); 
		var data = $.shine.serializeObject("#form");
		
		$.ajax({
			type: "POST",
			url: _url,
			data: data, dataType: "JSON",
		}).error(function(event, XMLHttpRequest, ajaxOptions, thrownError){
			layer.close(msgIndex);
		}).done(function(result){
			if(result.error != null  && result.error != undefined) {
				layer.msg('发生错误！', { icon: 2, time: 1000, shade: [0] }, function(){ layer.close(msgIndex); }); 
			} else {
				oTable.ajax.reload();
				layer.close(msgIndex);
				layer.close(dialogIndex) ;
				$.gritter.add({
					text: '<i class="ace-icon fa fa-check bigger-150"></i>&nbsp;&nbsp;&nbsp;<span class="bigger-150">'+result.message+'</span>',
					class_name: 'gritter-success'
				});
			}
		});
	}
}


function del(id) {
	$.dialog.confirm('你确定要删除吗？', function(){
		$.ajax({
			type: "GET", dataType: "JSON",
			url: "${ctx}/admin/sys/user/delete/"+id,
		}).error(function(event, XMLHttpRequest, ajaxOptions, thrownError){
			layer.msg('删除发生错误！', { icon: 2, time: 1000, shade: [0] }); 
		}).done(function(result){
			if(result.error != null  && result.error != undefined) {
				layer.msg('删除发生错误！', { icon: 2, time: 1000, shade: [0] }); 
			} else {
				oTable.ajax.reload();
				$.gritter.add({
					text: '<i class="ace-icon fa fa-check bigger-150"></i>&nbsp;&nbsp;&nbsp;<span class="bigger-150">'+result.message+'</span>',
					class_name: 'gritter-success'
				});
			}
		});
	}, function(){
	    $.dialog.tips('执行取消操作');
	});
}

function edit() {
	var rows = oTable.rows(".selected") ;
	if(undefined == rows || rows.data().length < 1) {
		$.gritter.add({
			text: '<i class="ace-icon fa fa-exclamation-triangle bigger-150"></i>&nbsp;&nbsp;&nbsp;<span class="bigger-150">请选择要编辑的行！</span>',
			class_name: 'gritter-warning'
		});
		return ;
	}
	if(rows.data().length > 1) {
		$.gritter.add({
			text: '<i class="ace-icon fa fa-exclamation-triangle bigger-150"></i>&nbsp;&nbsp;&nbsp;<span class="bigger-150">只能编辑一行！</span>',
			class_name: 'gritter-warning'
		});
		return ;
	}
	formDialog(rows.data()[0].id) ;
}

function batchDel(type) {
	var ids = [] ;
	var rows = oTable.rows(".selected") ;
	$.each(rows.data(), function(){ 
		ids.push(this.id);
	});
	if(ids.length > 0) {
		$.dialog.confirm('你确定要执行该操作吗？', function(){
			deleteForPhysical(type, ids) ;
		}, function(){
		    $.dialog.tips('操作取消');
		});
	} else {
		$.gritter.add({
			text: '<i class="ace-icon fa fa-check bigger-150"></i>&nbsp;&nbsp;&nbsp;<span class="bigger-150">请选中要操作的数据！</span>',
			class_name: 'gritter-warning'
		});
	}
}

function deleteForPhysical(type, ids) {
	var _url = "${ctx}/admin/sys/user/delete?type=true" ;
	//物理删除
	if(undefined != type && type == true) {
		_url = "${ctx}/admin/sys/user/deleteForPhysical" ;
	}
	//恢复已删除用户
	if(undefined != type && type == false) {
		_url = "${ctx}/admin/sys/user/delete?type=false" ;
	}
	
	$.ajax({
		type: "POST", dataType: "JSON", data: {"ids" : ids.join(',')},
		url: _url,
	}).error(function(event, XMLHttpRequest, ajaxOptions, thrownError){
		layer.msg('操作发生错误！', { icon: 2, time: 1000, shade: [0] }); 
	}).done(function(result){
		if(result.error != null  && result.error != undefined) {
			layer.msg('操作发生错误！', { icon: 2, time: 1000, shade: [0] }); 
		} else {
			$("#oTable thead tr th input:checkbox").attr("checked", false);
			oTable.ajax.reload();
			$.gritter.add({
				text: '<i class="ace-icon fa fa-check bigger-150"></i>&nbsp;&nbsp;&nbsp;<span class="bigger-150">'+result.message+'</span>',
				class_name: 'gritter-success'
			});
		}
	});
}

function searchDeleted() {
	$('#deleted').val('1');oSearch();
	$(".py-btn").show() ;
}
function searchDeleted(type) {
	if(type=="deleted"){$('#deleted').val('1');$(".py-btn").show();$(".del-btn").hide();}
	else if(type=="all"){$('#deleted').val('');$(".py-btn").hide();$(".del-btn").show();}
	oSearch();
	
}

function quickSearch() {
	var wait = 0 ;
	$("#quickSearch").on("keyup", function() {
		if(undefined != $(this).val()) {
			clearTimeout(wait);  
			wait = setTimeout(function(){
				oTable.ajax.reload();
			},500);
		}
	});
}
function oSearch() {
	oTable.ajax.reload();
}
function resetSearch() {
	$(".py-btn").hide();$(".del-btn").show();
	
	$("#search_form").formReset();
	oTable.ajax.reload();
}

</script>
